<?php

namespace backend\models\form;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Log;

/**
 * LogForm represents the model behind the search form about `backend\models\Log`.
 */
class LogForm extends Log {

    public $start_time;
    public $end_time;
    public $keyword;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'level'], 'integer'],
            [['category', 'prefix', 'message'], 'safe'],
            [['log_time'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params) {
        $query = Log::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        if (!empty($params['level'])) {
            $query->andFilterWhere([
                'level' => $params['level'],
            ]);
        }

        if (!empty($params['keyword'])) {
            $query->andFilterWhere(['like', 'category', $params['keyword']])
                    ->orFilterWhere(['like', 'message', $params['keyword']]);
        }

        if (!empty($params['start_time'])) {
            $startTime = strtotime($params['start_time']);
            $query->andFilterWhere(['>=', 'log_time', $startTime]);
        }

        if (!empty($params['end_time'])) {
            $endTime = strtotime($params['end_time']);
            $query->andFilterWhere(['<', 'log_time', $endTime]);
        }

        $query->orderBy('id DESC');

        return $dataProvider;
    }

}
